package com.hnqcgczy.sgzshop.dbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class MyTransaction {
    private Connection connection;
    ComboPooledDataSource dataSource;
    public MyTransaction(boolean isAutoCommit) {
        try {
            //connection=new DBImpl().getConnectionByMySQL();//立即实例化赋值  给成员属性赋值
            dataSource=new ComboPooledDataSource();
            connection=dataSource.getConnection();

            this.connection.setAutoCommit(isAutoCommit);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public Connection getConn()throws SQLException{
        return connection;
    }

    /**
     * 关闭数据库连接
     * @throws SQLException
     */
    public void closeConn() throws SQLException {

//            if(connection!=null&&!connection.isClosed()){
//                connection.close();
//            }
        dataSource.close();

    }

    public void commit()throws SQLException{
       if(connection!=null){
           connection.commit();
       }
    }

    public void rollback()throws SQLException{
        if(connection!=null){
            connection.rollback();
        }
    }

    public static void main(String[] args) {
        try {
            Connection conn = new MyTransaction(true).getConn();
            System.out.println(conn.isClosed());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }




}
